<!--
  组件名称：历史记录
 -->
<template>
  <div :class="{'full-page':isFullPage}">
    <el-row style="padding:20px 0px;">
      <el-col :span="8" style="width:180px;margin-right:4px;">
        <!-- 选择器：查询类型选择 -->
        <el-select v-if="queryTypeSelectIsShow" size="mini" v-model="queryType" @change="isLoading=true;creactColumns();getData();">
          <el-option :value="1" label="按年度查询">
          </el-option>
          <el-option :value="2" label="按时间范围查询">
          </el-option>
        </el-select>
      </el-col>
      <el-col>
        <!-- 时间范围选择器 -->
        <el-date-picker size="mini" style="width:345px;" v-show="queryType==2" v-model="dateScope" type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00']" @change="isLoading=true;creactColumns();getData();" :clearable="false" :editable="false" :unlink-panels="false" />
        <!-- 年份选择 -->
        <el-select size="mini" v-show="queryType==1" v-model="choseYear" placeholder="请选择年份" @change="isLoading=true;creactColumns();getData();">
          <el-option v-for="year in yearArray" :key="year" :label="year" :value="year">
          </el-option>
        </el-select>
        <!-- 全屏控制 -->
        <el-button size="mini" @click="isFullPage=!isFullPage">{{isFullPage?'取消放大':'放大'}}</el-button>
        <img src="" alt="">
        <img src="" alt="">
        <el-button size="mini" @click="exportTable()" style="margin-left:0px;">导出</el-button>
      </el-col>
    </el-row>

    <!--这里是表格-->
    <!--设置全屏-->
    <el-table class="history-table" :stripe='this.stripe' :class="{'full-page1':isFullPage}" :show-summary="addition.needSummation" :summary-method="getSummaries" v-loading="isLoading" element-loading-background="rgba(0, 0, 0, 0.3)" :data="data" border :max-height="isFullPage?getFullPageMaxHeight():300" style="width: 670px; background-color:transparent;" :row-style="{'background-color':'rgba(255,255,255,0)'}" :header-row-style="{'background-color':'rgba(255,255,255,0)'}" :header-cell-style="({row, column, rowIndex, columnIndex})=>{return column['property']!='dateDay'?{'background-color':'rgba(255,255,255,0)'}:{'background-color':'none'}}" :cell-style="({row, column, rowIndex, columnIndex})=>{return column['property']!='dateDay'?{'background-color':'rgba(255,255,255,0)'}:{'background-color':'#fff'}}"><!--rgba(20, 34, 71, 0.2)-->
      <!-- 第一列显示几号 -->
      <el-table-column label="日期" width="60px" prop="dateDay" fixed :formatter="(row,col,val,index)=>(index+1)+'号'" />
      <!-- 其他列头显示年月 -->
      <el-table-column v-for="col in column" width="125px" :key="col['label']" :prop="col['prop']" :label="col['label']">
        <!-- 内容显示使用自定义组件 -->
        <template slot-scope="scope">
          <!-- 每个格子一个弹窗 -->
          <el-popover v-if="false" popper-class="PopUpBox" trigger="click" placement="top">
            <!-- 每个格子的弹窗使用年月与日分别作为坐标存储状态 -->
            <slot v-if="popoverStates[scope.column['property']+''+(scope.$index+1)]" style="z-index:100;" :row="row" :src="assembleParam(scope.column['property'], scope.$index+1)" :addition="addition" />
            <!-- 点击触发 -->
            <div slot="reference" class="name-wrapper" @click="popoverClick(choseYear,scope.column['property'],scope.$index+1,row['STCD'])">
              <!-- 显示值使用tag -->
              <el-tag size="medium">{{ formatter(scope.row,scope.row[col['prop']],scope.$index) }}
              </el-tag>
            </div>
          </el-popover>
          <div @click="clickCel(scope.column['property'],scope.$index+1,row['STCD'])">
            <!-- 显示值使用tag -->
            <el-tag size="medium">{{ formatter(scope.row,scope.row[col['prop']],scope.$index) }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-drag class="dialog-history" :show-close="false" :append-to-body="true" :modal-append-to-body="false" :visible.sync="dialogFormVisible">
      <!-- 基本数据窗口 -->
      <slot v-if="dialogFormVisible" :title="dialogFormData.title" style="z-index:100;" :row="row" :src="assembleParam(dialogFormData.yearMonth, dialogFormData.day)" :addition="addition" />
      <a @click="dialogFormVisible = false" class="ol-popup-closer" style="display:block;top: 70px;right:-140px;color:#fff;"></a>

    </el-dialog>
  </div>
</template>
<script>
import DateDataLineChart from './DateDataLineChart'
import { exportJsonToExcel } from './../../../excel/Export2Excel'
import { mapGetters } from 'vuex'
// 月份与索引转换
const month2Index = [
  '00',
  '01',
  '02',
  '03',
  '04',
  '05',
  '06',
  '07',
  '08',
  '09',
  '10',
  '11',
  '12'
]
// 创建初始填充数据
let createInitData = function (v) {
  let data = []
  let nowYear = new Date().getFullYear()
  for (var j = 1; j <= 31; j++) {
    let o = {}
    for (var i = 1; i <= 12; i++) {
      o[nowYear + month2Index[i]] = v
    }
    data.push(o)
  }
  return data
}
export default {
  // 名称
  name: 'HistoryData',
  props: [
    // 数据集
    'row',
    // 数据源
    'src',
    // 附加数据
    'addition'
  ],
  data () {
    return {
      stripe: true,
      // 数据
      dialogFormData: {
        title: '',
        yearMonth: '',
        day: '',
        id: ''
      },
      // 弹窗显示
      dialogFormVisible: false,
      // 查询类型选择框是否显示
      queryTypeSelectIsShow: true,
      // 是否全屏
      isFullPage: false,
      // 是否加载中
      isLoading: false,
      queryType: 2,
      // 查询事件范围
      dateScope: [
        // 起始时间
        new Date(new Date().getFullYear(), 0, 1, 0, 0, 0),
        // 结束时间
        new Date()
      ],
      // 当前选择年
      choseYear: new Date().getFullYear(),
      // 格式
      column: {},
      // 数据
      data: createInitData('——'),
      // 范围数据
      scopeData: [],
      // 弹出框显示状态控制
      popoverStates: {}
    }
  },
  components: { DateDataLineChart },
  mounted () {
    // 时间范围查询接口不存在
    if (!this.src['dateScope']) {
      // 隐藏类型选择框
      this.queryTypeSelectIsShow = false
      // 设为年查
      this.queryType = 1
    }
    // 年查询接口不存在
    if (!this.src['yearQuery']) {
      // 隐藏类型选择框
      this.queryTypeSelectIsShow = false
      // 设为范围查
      this.queryType = 2
    }
    // 设定初始选择月
    this.creactColumns()
    this.getData()
  },
  watch: {
    row: function () {
      // 时间范围查询接口不存在
      if (!this.src['dateScope']) {
        // 隐藏类型选择框
        this.queryTypeSelectIsShow = false
        // 设为年查
        this.queryType = 1
      }
      // 年查询接口不存在
      if (!this.src['yearQuery']) {
        // 隐藏类型选择框
        this.queryTypeSelectIsShow = false
        // 设为范围查
        this.queryType = 2
      }
      // 设定初始选择月
      this.creactColumns()
      this.getData()
    },
    popoverStates: function () { }
  },
  computed: {
    ...mapGetters([
      // 'isFullPage'
    ]),
    yearArray () {
      let array = []
      for (var i = new Date().getFullYear(); i > 1970; i--) {
        array.push(i)
      }
      return array
    }
  },
  methods: {
    exportTable () {
      require.ensure([], () => {
        // const filterVal = []
        // const tHeader = []
        if (this.addition['showKey'] === 'Q1') {
          const tHeader = [
            '站名',
            '监测时间',
            'O2(PPM)',
            'CO(PPM)',
            'CH4(PPM)',
            'H2S(PPM)'
          ]
          const filterVal = ['STNM', 'YMDHM', 'Q1', 'Q2', 'Q3', 'Q4']
          const list = this.scopeData
          const data = this.formatJson(filterVal, list)
          exportJsonToExcel(tHeader, data, '水务信息列表')
        } else {
          const tHeader = [
            this.addition['stationName'],
            this.addition['chartDate'],
            this.addition['chartDataName']
          ]
          const filterVal = [
            this.addition['charStationName'],
            this.addition['dateKey'],
            this.addition['chartShowKey']
          ]
          const list = this.scopeData
          const data = this.formatJson(filterVal, list)
          exportJsonToExcel(tHeader, data, '水务信息列表')
        }
      })
    },
    clickCel (yearMonth, day, id) {
      this.$set(this.dialogFormData, 'title', yearMonth + (day < 10 ? ('0' + day) : day) + '历史数据')
      this.$set(this.dialogFormData, 'yearMonth', yearMonth)
      this.$set(this.dialogFormData, 'day', day)
      this.$set(this.dialogFormData, 'id', id)
      this.dialogFormVisible = true
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    // 计算全屏高度
    getFullPageMaxHeight () {
      return document.documentElement.clientHeight * 0.70
    },
    // 计算合计值函数
    getSummaries (param) {
      // 解构字段与数据
      const { columns, data } = param
      // 结果集合
      const sums = []
      // 遍历字段
      columns.forEach((column, index) => {
        // 第一行跳过
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        // 数字转换
        const values = data.map(item => Number(item[column.property]))
        // 筛选累加
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0).toFixed(2)
      })

      return sums
    },
    assembleParam (yearMonth, day) {
      let date =
        yearMonth.slice(0, 4) + '-' + yearMonth.slice(4, 6) + '-' + day
      // 组装
      return { param: { date, stcd: this.row[this.addition['primaryKey']] } }
    },
    // 触发弹窗
    popoverClick (year, month, day, id) {
      // 检查弹窗状态不存在
      if (this.popoverStates[month + '' + day] === undefined) {
        // 初始化
        this.$set(this.popoverStates, month + '' + day, false)
      }
      // 遍历全部
      for (var i in this.popoverStates) {
        // 是当前处理就跳过
        if (i === month + '' + day) continue
        // 设为关闭
        this.$set(this.popoverStates, i, false)
      }
      // 当前处理设为打开
      this.$set(
        this.popoverStates,
        month + '' + day,
        !this.popoverStates[month + '' + day]
      )
    },
    formatter (row, val, index) {
      // 是空的就用破折号占位;其实初始化的时候已经置0
      return val === '' || val === undefined ? '——' : val
    },
    creactColumns () {
      let column = []
      let now = new Date()

      // 现在月份
      let nowMonth = now.getMonth() + 1
      // 按照年份
      if (this.queryType === 1) {
        for (let j = 1; j <= 12; j++) {
          // 当前年且处理月数等于当月
          if (now.getFullYear() === this.choseYear && nowMonth < j) {
            continue
          }
          column.push({
            label: this.choseYear + '年' + j + '月',
            prop: this.choseYear + month2Index[j]
          })
        }
        this.column = column
        return
      }
      // 按照范围
      let startDate = this.dateScope[0]
      let endDate = this.dateScope[1]
      let startYear = startDate.getFullYear()
      let endYear = endDate.getFullYear()
      let startMonth = startDate.getMonth() + 1
      let endMonth = endDate.getMonth() + 1
      for (var i = startYear; i <= endYear; i++) {
        for (let j = 1; j <= 12; j++) {
          // 当前年为起始年且处理月数小于起始月份
          if (i === startYear && j < startMonth) {
            continue
          }
          // 当前年为结束年年且处理月数大于于结束月份
          if (i === endYear && j > endMonth) {
            continue
          }
          column.push({
            label: i + '年' + j + '月',
            prop: i + month2Index[j]
          })
        }
      }
      this.column = column
    },
    // 获取数据的方法
    getData () {
      // 加载中遮罩
      this.isLoading = true
      let _this = this
      // 请求地址
      let { url, param } = this.$handleSrc(
        this.queryType === 1 // 按年查询接口
          ? this.src['yearQuery']
          // 范围查询的接口
          : this.src['dateScope'],
        {
          // 当前处理站数据
          row: this.row,
          // 选中年
          choseYear: this.choseYear,
          // 时间范围
          dateScope: this.dateScope
        }
      )
      // 发起请求
      this.$postJSON(url, param).then(data => {
        // 保存查询结果
        _this.$set(_this, 'scopeData', data)
        // 重置数据
        _this.$set(_this, 'data', createInitData('0')) // ——
        // 按年度查询场合
        for (let o of data) {
          // 日期
          let dateObj = new Date(o[_this.addition.dateKey])
          let year = dateObj.getFullYear()
          let month = dateObj.getMonth() + 1
          let day = dateObj.getDate()
          try {
            _this.$set(
              _this.data[day - 1],
              year + month2Index[month],
              o[_this.addition.showKey]
            )
          } catch (error) {
            console.error(error)
          }
        }
        this.isLoading = false
      })
    }
  }
}
</script>
<style scoped>
.aside-main {
  background-color: #ffffff00;
  float: left;
  padding: 20px 0px;
}

.aside-table .warning {
  color: red;
  font-weight: bold;
}

.real-time {
  color: #00d9e7;
  font-size: 14px;
}
.real-time-title {
  font-size: 18px;
  font-weight: bold;
  color: #00d9e7;
}
.monitoring1 {
  color: #fff;
  font-size: 14px;
  width: 100px;
}
.monitoring1-data {
  color: red;
  font-weight: bold;
  font-size: 14px;
  padding-left: 0px;
}
.circular {
  width: 110px;
  height: 110px;
  border-radius: 50%;
  border: 6px solid #00d8e7;
  color: #00d8e7;
  font-weight: bold;
  font-size: 20px;
  text-align: center;
  line-height: 110px;
}
.date-col {
  background-color: #303133b0;
}
.el-tabs__content {
  padding: 0 20px;
}
/*表格隔行颜色和hover时颜色*/
.history-table>>>.el-table__row:hover{
  background: #fdf5e6!important;
}
.history-table>>>.el-table__row--striped{
  background: #f3f9ff!important;
}
.history-table>>>.el-tag{
  background: transparent;
}
/*历史详情*/
.dialog-history{
  position: relative;
  width: 950px;
  overflow: hidden;
}
.dialog-history>>>.history-card span:first-child{
  display: none;
}
.dialog-history>>>#pane-1 span{
  display: block;
}
/* .dialog-history>>>.history-card span{
  display: block;
  display: none;
  height: 32px;
  line-height: 32px;
  background-color: #247df7;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  color: #fff!important;
} */
.dialog-history>>>.history-card{
  border:none!important;
}
.dialog-history>>>.el-table__empty-block .el-table__empty-text{
  background-color: #fff;
  color: #000!important;
  font-weight: bold;
  display: block;
}
</style>
<style>
.PopUpBox {
  background-color: #0f1c3e;
  border: 2px solid rgb(96, 203, 248);
}
::-webkit-scrollbar {
  /* width: 10px;
  height: 10px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 10px; */
}
::-webkit-scrollbar-corner {
  background-color: transparent;
}
::-webkit-scrollbar-thumb {
  width: 8px;
  height: 8px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 10px;
}
/**
 * 全屏
 */
.full-page {
  /* background-image: url(/static/img/beijingtu.bd4277a.jpg); */
  /* position: fixed;
  top: 60px;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 10; */
  height: 80vh;
  width:60vw;
}
.full-page1{
  width:100%!important;
  height: 100%;
}
</style>
